/*
 * @Author: hongbin
 * @Date: 2022-11-19 14:02:15
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-30 16:50:12
 * @Description:axios
 */
import axios, { AxiosRequestConfig } from "axios";
// const baseURL = "http://localhost:3000/api";
const baseURL = `${process.env.NEXT_PUBLIC_HREF}`;
// const baseURL = "http://hongbin.xyz:3000/api";

axios.defaults.baseURL = baseURL;

axios.interceptors.request.use((config: AxiosRequestConfig) => {
    if (typeof window !== "undefined") {
        // config.headers.Authorization = getLocalJWT();
    }
    return config;
});

export default axios;
// export const { get, post } = axios;

export const get: <T = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise<T> = async (url, config) =>
    await axios
        .get(url, config)
        .then((res) => res)
        .catch((err) => {
            console.error(url + " 请求出错", err, err.response);
            return err.response;
        });

//不会有catch 单端返回有没有err即可
export const post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig | undefined) => Promise<T> = (
    ...props
) => {
    return new Promise((resolve, reject) => {
        axios
            .post(...props)
            .then((res) => resolve(res.data))
            .catch((err) => {
                // reject(err); // 配合await 使用catch时会遇到debug 😡
                console.error("request" + props[0] + " err", err, err.response);
                const message = err.response?.data?.message;
                if (message) console.log({ message });
                reject({ err: err.response });
            });
    });
};
